﻿@page "/"
@inject Task<HttpClient> tHttp
@inject ModalService _modalService

<div class="col-md-12" style="max-height:100%">
    <Spin Spinning=Loading>
        <MarkdownEditor
                        Value="@MarkdownValue" 
                        ValueChanged="@OnMarkdownValueChanged"
                        ImageUploadEndpoint="@UploadService"
                        ImageUploadChanged="@OnImageUploadChanged"
                        ImageUploadStarted="@OnImageUploadStarted"
                        ImageUploadProgressed="@OnImageUploadProgressed"
                        ImageUploadEnded="@OnImageUploadEnded"
                        UploadImage="true"
                        @ref="MarkdownEditor">
                        <Toolbar>
                <MarkdownToolbarButton Action="MarkdownAction.Bold" />
                <MarkdownToolbarButton Action="MarkdownAction.Italic" />
                <MarkdownToolbarButton Action="MarkdownAction.Code" />
                <MarkdownToolbarButton Separator Action="MarkdownAction.Quote" />
                <MarkdownToolbarButton Action="MarkdownAction.UnorderedList" />
                <MarkdownToolbarButton Action="MarkdownAction.OrderedList" />
                <MarkdownToolbarButton Action="MarkdownAction.Link" />
                <MarkdownToolbarButton Separator Action="MarkdownAction.Image" Icon="fa fa-image" />
                <MarkdownToolbarButton Action="MarkdownAction.Table" />
                <MarkdownToolbarButton Action="MarkdownAction.Preview" Title="Toggle Preview (Ctrl-P)" />
                <MarkdownToolbarButton Name="@(Constants.BaseAddress+"doc")" Icon="fa fab fa-search" Title="快捷键说明" />
                <MarkdownToolbarButton Name="@(Constants.BaseAddress+"config")" Icon="fa fab fa-file-code" Title="config" />
                <MarkdownToolbarButton Name="@(Constants.BaseAddress+"share")" Icon="fa fab fa-share" Title="share" />
                        </Toolbar>
        </MarkdownEditor>
    </Spin>

    @*<button @onclick="ChangeText">Change text</button>
    <hr />


    <h3>Result</h3>
    @((MarkupString)MarkdownHtml)

    <h3>Value</h3>
    @((MarkupString)MarkdownValue)*@

    @{
        var name = string.IsNullOrWhiteSpace(this.FilePath) ? "folder" : "file";
    }

    @*删除*@
    <Modal Title="Delete"
           Visible="@delete_visible"
           OnOk="() => Del(true,null)"
           OnCancel="() => Del(false,null)"
    >
        <p>Are you sure delete this @name?</p>
        <p>@(string.IsNullOrWhiteSpace(this.FilePath) ? Path : FilePath)</p>
    </Modal>
    

    @*Rename or new*@
    <Modal Title="@ModalTitle"
           Visible="@Modal_visible"
           OnOk="() => ReNameOrNew(true)"
           OnCancel="() => ReNameOrNew(false)">

        <RadioGroup @bind-Value="isFolder" ButtonStyle="@RadioButtonStyle.Solid">
            <Radio RadioButton Value="true">Folder</Radio>
            <Radio RadioButton Value="false">File</Radio>
        </RadioGroup>
        <br />
        <br />
        <Input Disabled="@oldDisabled" @bind-Value="@oldValue">
        <Prefix> Current Path： </Prefix>
        </Input>
        <br />
        <br />
        <Input @bind-Value="@newValue" OnPressEnter="()=>ReNameOrNew(true)">
            <Prefix> New Path： </Prefix>
        </Input>

        <br />
        <br />


        
        @*<Switch Checked="@isFolder" 
            CheckedChildren="Folder" UnCheckedChildren="File" OnChange="e => SwitchChange(e)" />
*@
    </Modal>

</div>

            @code {

    string _FilePath = string.Empty;
    public bool Loading { get; set; }
    public bool delete_visible { get; set; }

    public bool IsChanged { get; set; }
    HttpClient Http;

    public string ModalTitle { get; set; }
    public bool Modal_visible { get; set; }
    public bool oldDisabled { get; set; }
    public string oldValue { get; set; }
    public string newValue { get; set; }

    private bool _isFolder { get; set; }
    public bool isFolder
    {
        get => _isFolder; 
        set
        {
            _isFolder = value;
            SwitchChange(value);
        }
    }

    [CascadingParameter(Name = "Path")]
    protected string Path { get; set; }

    [CascadingParameter(Name = "PWD")]
    protected string PWD { get; set; }

    [CascadingParameter(Name = "FilePath")]
    protected string FilePath { get => _FilePath;
        set
        {
            if (
                    this.IsChanged
                    && !string.IsNullOrEmpty(this.MarkdownValue)
                    && !string.IsNullOrWhiteSpace(_FilePath))
            {
                this.IsChanged = false;
                Http.PostAsJsonAsync($"/File/Content", new FileSave
                    {
                        Type = FileSaveEnum.Modify,
                        FileName = this.FilePath,
                        Value = this.MarkdownValue ?? ""
                    });
            }
            _FilePath = value;
            _ = ChangeText();
        }
    }


    public MarkdownEditor? MarkdownEditor { get; set; }
    public string? MarkdownValue { get; set; }
    public string? MarkdownHtml { get; set; }

    public string UploadService = Constants.BaseAddress + "file/upload";

    RenderFragment icon = @<Icon Type="exclamation-circle" Theme="outline"></Icon>;

    protected override async void OnInitialized()
    {
        Console.WriteLine("index OnInitialized");
        this.Http = await tHttp;

        JSLibrary.Ctrl_S_Event += (s, e) => Save(s, null);
        JSLibrary.Ctrl_N_Event += New;
        JSLibrary.Ctrl_Del_Event += (s, e) => Del(s, e);
        JSLibrary.Ctrl_F2_Event += ReName;
        JSLibrary.Ctrl_Q_Event += Share;
        JSLibrary.Ctrl_P_Event += (s, e) =>
        {
            js.InvokeVoidAsync("easyMDE.togglePreview");
        };

        this.MarkdownHtml = Markdig.Markdown.ToHtml(MarkdownValue ?? string.Empty);
        base.OnInitialized();
        await Task.Delay(500);
        await this.MarkdownEditor!.SetValueAsync(string.Empty);
    }

    public void Dispose()
    {
        JSLibrary.Ctrl_S_Event -= (s, e) => Save(s, null);
        JSLibrary.Ctrl_N_Event -= New;
        JSLibrary.Ctrl_Del_Event -= (s, e) => Del(s, e);
        JSLibrary.Ctrl_F2_Event -= ReName;
        JSLibrary.Ctrl_Q_Event -= Share;
        JSLibrary.Ctrl_P_Event -= (s, e) =>
        {
            js.InvokeVoidAsync("easyMDE.togglePreview");
        };
    }

    async Task OnMarkdownValueChanged(string value)
    {
        this.IsChanged = true;
        this.MarkdownValue = value;
    }

    async Task ChangeText()
    {
        await js.InvokeVoidAsync("localStorage.setItem", "currentpath", this.PWD);
        this.Loading = true;
        try
        {
            HttpClient Http = await tHttp;
            this.MarkdownValue =
            string.IsNullOrWhiteSpace(FilePath) ? "" :
            await Http.GetStringAsync($"/File/Content/{Uri.EscapeDataString(this.FilePath)}");
            await this.MarkdownEditor!.SetValueAsync(this.MarkdownValue);
            this.IsChanged = false;
        }
        catch (Exception _)
        {
            
        }
        this.Loading = false;
        StateHasChanged();
    }

    async Task Save(object? sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(this.FilePath))
        {
            return;
        }

        this.Loading = true;
        HttpClient Http = await tHttp;

        var response = await Http.PostAsJsonAsync($"/File/Content", new FileSave
        {
            Type = FileSaveEnum.Modify,
            FileName = this.FilePath,
            Value = this.MarkdownValue ?? ""
        });

        if (await this.ExcuterResponse(response))
        {
            // chen g
        }

        this.Loading = false;

        StateHasChanged();
    }

    async Task Del(object? sender, EventArgs e)
    {
        HttpClient Http = await tHttp;
        if (string.IsNullOrWhiteSpace(this.FilePath) && string.IsNullOrWhiteSpace(this.Path))
        {
            return;
        }

        if (sender == null)
        {
            this.delete_visible = true;
            StateHasChanged();
            return;
        }

        this.delete_visible = false;

        if ((bool)sender == true)
        {
            this.Loading = true;

            var response = await Http.PostAsJsonAsync($"/File/Content", new FileSave
                {
                    Type = string.IsNullOrWhiteSpace(this.FilePath) ? FileSaveEnum.DeleteFolder : FileSaveEnum.Delete,
                    FileName = string.IsNullOrWhiteSpace(this.FilePath) ? this.Path : this.FilePath
                });

            if (await this.ExcuterResponse(response))
            {
                // chen g
            }

            this.Loading = false;
            JSLibrary.F5Event();
            StateHasChanged();
        }
    }


    void New(object? sender, EventArgs e)
    {
        this.oldDisabled = true;
        var isFolder = string.IsNullOrWhiteSpace(this.FilePath) ? true : false;
        if (sender == null)
        {
            this.isFolder = isFolder;
            Modal_visible = true;
            if (isFolder)
            {
                ModalTitle = "Create Folder";
                oldValue = Path;
            }
            else
            {
                ModalTitle = "Create File";
                oldValue = FilePath;
            }
            newValue = oldValue;
            StateHasChanged();
            return;
        }

        Modal_visible = false;

        StateHasChanged();
    }

    void ReName(object? sender, EventArgs e)
    {
        this.oldDisabled = false;
        var isFolder = string.IsNullOrWhiteSpace(this.FilePath) ? true : false;
        if (sender == null)
        {
            Modal_visible = true;
            this.isFolder = isFolder;
            if (isFolder)
            {
                ModalTitle = "ReName Folder";
                oldValue = Path;
            }
            else
            {
                ModalTitle = "ReName File";
                oldValue = FilePath;
            }
            newValue = oldValue;
            StateHasChanged();
            return;
        }

        Modal_visible = false;

        StateHasChanged();
    }

    void Share(object? sender, EventArgs e)
    {
        js.InvokeVoidAsync("openBrowserUrl", "/share", "share");
    }

    void SwitchChange(bool v)
    {
        if (this.oldDisabled)
        {
            ModalTitle = isFolder ? "Create Folder" : "Create File";
        }
        else
        {
            ModalTitle = isFolder ? "ReName Folder" : "ReName File";
        }
    }

    async Task ReNameOrNew(bool isOk)
    {
        Modal_visible = false;
        if (isOk == true)
        {
            this.Loading = true;

            FileSaveEnum type;

            if (this.oldDisabled)
            {
                type = isFolder ? FileSaveEnum.CreateFolder : FileSaveEnum.Create;
            }
            else
            {
                type = isFolder ? FileSaveEnum.ReNameFolder : FileSaveEnum.ReName;
            }

            HttpClient Http = await tHttp;

            var response = await Http.PostAsJsonAsync($"/File/Content", new FileSave
                {
                    Type = type,
                    FileName = (type == FileSaveEnum.ReNameFolder || type == FileSaveEnum.ReName) ? oldValue : newValue,
                    Value = (type == FileSaveEnum.ReNameFolder || type == FileSaveEnum.ReName) ? newValue : ""
                });

            if (await this.ExcuterResponse(response))
            {
                // chen g
            }

            this.Loading = false;
            JSLibrary.F5Event();
        }
        StateHasChanged();
    }


    async Task<bool> ExcuterResponse(HttpResponseMessage httpResponse)
    {

        var result = await httpResponse.Content.ReadAsStringAsync();

        if (string.Compare(result, "ok", true) == 0)
        {
            _ = _message.Success("This is a excuter success message");
            return true;
        }
        else
        {
            _ = _message.Error(result);
            return false;
        }
    }
}


@*上传文件*@
@code{
    Task OnImageUploadChanged(FileChangedEventArgs e)
    {
        this.StateHasChanged();
        return Task.CompletedTask;
    }

    Task OnImageUploadStarted(FileStartedEventArgs e)
    {
        Console.WriteLine($"Started Image: {e.File.Name}");
        return Task.CompletedTask;
    }

    Task OnImageUploadProgressed(FileProgressedEventArgs e)
    {
        Console.WriteLine($"Image: {e.File.Name} Progress: {(int)e.Percentage}");
        return Task.CompletedTask;
    }

    Task OnImageUploadEnded(FileEndedEventArgs e)
    {
        Console.WriteLine($"Finished Image: {e.File.Name}, Success: {e.Success}");
        return Task.CompletedTask;
    }
}

